package cn.tedu._03vehicle.base.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class timecount implements HandlerInterceptor
{
    private static int mcount=3;
    private static int mtime=60;
    private ConcurrentHashMap<String,Integer> count=new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, LocalDateTime> lasttime=new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("网站限流");
        String ip=request.getRemoteAddr();
        LocalDateTime ltime=lasttime.get(ip);
        if(ltime==null||LocalDateTime.now().isAfter(ltime.plusSeconds(mtime)));
        {
            count.put(ip,0);
            lasttime.put(ip,LocalDateTime.now());
        }
        Integer co=count.get(ip);
        co=co+1;
        if(co>mcount)
        {
            throw new RuntimeException("访问过于频繁");
        }
        return true;
    }
}
